package net.appportal.ant.tasks;

import java.util.Vector;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

import ca.beq.util.win32.registry.RegistryException;
import ca.beq.util.win32.registry.RegistryKey;
import ca.beq.util.win32.registry.RegistryValue;
import ca.beq.util.win32.registry.RootKey;

public class NsisTask extends Task
{
	private final String TASK_NAME= "nsis"; 
	private Vector tasks = new Vector();
	private boolean verbose = false;
	private boolean failonerror = true;
	
	private String property = "";
	private String key = "";
	private String name = "";
	private String nsisfile = "";
	
	/**
	 * 
	 * @param failonerror
	 */
	public void setFailonerror( boolean failonerror ) 
	{
		this.failonerror = failonerror;
	}	
	
	/**
	 * 
	 * @param property
	 */
	public void setProperty( String property ) 
	{
		this.property = property;
	}	
	
	/**
	 * 
	 * @param verbose
	 */
	public void setVerbose( boolean verbose )
	{
		this.verbose = verbose;
	}
	
	/**
	 * 
	 * @param key
	 */
	public void setKey( String key )
	{
		this.key = key;
	}
	
	/**
	 * 
	 * @param key
	 */
	public void setName( String name )
	{
		this.name = name;
	}
	
	/**
	 * 
	 * @param nsisfile
	 */
	public void setNsisfile( String nsisfile )
	{
		this.nsisfile = nsisfile;
	}
	
	/**
	 * 
	 * @throws  BuildException
	 */
	public void execute() throws BuildException
	{
		try 
		{
			name = "SOFTWARE\\NSIS";
			key = "";
			
			if ( nsisfile == null || nsisfile.equals( "" ) )
				throw new BuildException( "The 'nsisfile' attribute is required with '"+ TASK_NAME+"'." );		
			
			String value = "";
			RegistryKey r = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE, name);
			if (verbose)
			{
				log("nsisfile : " + nsisfile);
			}
			if(!r.hasValue(key))
				throw new BuildException( "Could not found NSIS install foler");	
			
		   RegistryValue v = r.getValue(key);  
		   value = v.toString();
		   value = value.replaceAll(":REG_SZ:", "").replaceAll(":REG_DWORD:", "");

		   if (verbose)
			{
				log("value : " + value);
			}
//			getProject().setUserProperty(property,value);
		} 
		catch (Exception e) 
		{
			if (failonerror)
			{
				log(e.getMessage());
				throw new BuildException(e);
			}
		}
	}

	public void addTask( Task task ) 
	{
	      tasks.addElement( task );		
	}
}